package com.milkshopbackend.milkshop.security;

import com.milkshopbackend.milkshop.util.JWTUtil;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationFilter.class);
    private final JWTUtil jwtUtil;

    // 定义不需要认证的路径前缀
    private static final List<String> PUBLIC_PATHS = Arrays.asList(
            "/api/user/login",
            "/api/user/register",
            "/api/user/send-reset-code",
            "/api/user/reset-password",
            "/api/products",
            "/api/categories",
            "/api/reviews",
            "/api/search",
            "/uploads",
            "/swagger-ui",
            "/swagger-resources",
            "/v3/api-docs"
    );

    public JwtAuthenticationFilter(JWTUtil jwtUtil) {
        this.jwtUtil = jwtUtil;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {

        // 1. 检查是否是公开路径
        if (isPublicPath(request.getRequestURI())) {
            logger.debug("Public path accessed: {}", request.getRequestURI());
            chain.doFilter(request, response);
            return;
        }

        // 2. 获取token
        String token = request.getHeader("Authorization");
        logger.debug("Received token: {}", token);

        // 3. 如果是需要认证的接口但没有token，返回401
        if (token == null || !token.startsWith("Bearer ")) {
            logger.debug("Protected endpoint accessed without valid token: {}", request.getRequestURI());
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "No valid token provided");
            return;
        }

        // 4. 验证token
        token = token.substring(7);
        try {
            if (!jwtUtil.validateToken(token)) {
                logger.debug("Token validation failed");
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid token");
                return;
            }

            Long userId = jwtUtil.getUserIdFromToken(token);
            String username = jwtUtil.getUsernameFromToken(token);
            logger.debug("Token validated for user: {} with ID: {}", username, userId);

            // 5. 设置认证信息
            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                        userId, null, new ArrayList<>());
                SecurityContextHolder.getContext().setAuthentication(authentication);
                logger.debug("Authentication set for user: {} with ID: {}", username, userId);
            }
        } catch (Exception e) {
            logger.error("Cannot set user authentication: {}", e);
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid token");
            return;
        }

        chain.doFilter(request, response);
    }

    /**
     * 检查请求路径是否是公开路径
     */
    private boolean isPublicPath(String uri) {
        return PUBLIC_PATHS.stream().anyMatch(uri::startsWith);
    }
}
